const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { userService, adminService } = require('../services');

/**
 * 创建用户
 */
const createUser = catchAsync(async (req, res) => {
  const user = await userService.createUser(req.body);
  res.status(httpStatus.CREATED).send(user);
});

/**
 * 获取用户列表
 */
const getUsers = catchAsync(async (req, res) => {
  // 构建筛选条件
  const filter = {};
  
  // 按用户名搜索
  if (req.query.name) {
    filter.name = { $regex: req.query.name, $options: 'i' };
  }
  
  // 按活动状态筛选
  if (req.query.isActive !== undefined) {
    filter.isActive = req.query.isActive === 'true';
  }
  
  // 按用户角色筛选
  if (req.query.role) {
    filter.role = req.query.role;
  }
  
  // 按健康目标筛选
  if (req.query.goal) {
    filter.goal = req.query.goal;
  }
  
  // 查询选项
  const options = {
    sortBy: req.query.sortBy,
    limit: req.query.limit,
    page: req.query.page,
    search: req.query.search,
  };
  
  const result = await userService.queryUsers(filter, options);
  
  res.send({
    error: 0,
    body: result,
    message: ''
  });
});

/**
 * 获取单个用户详情
 */
const getUser = catchAsync(async (req, res) => {
  console.log('获取单个用户信息，用户ID:', req.params.userId);
  
  const user = await userService.getUserById(req.params.userId);
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, '用户未找到');
  }
  
  console.log('成功获取单个用户信息，用户ID:', req.params.userId);
  
  res.send({
    error: 0,
    body: user,
    message: ''
  });
});

/**
 * 更新用户信息
 */
const updateUser = catchAsync(async (req, res) => {
  console.log('更新用户信息，用户ID:', req.params.userId, '请求数据:', JSON.stringify(req.body));
  
  const user = await userService.updateUserById(req.params.userId, req.body);
  
  console.log('成功更新用户信息，用户ID:', req.params.userId);
  
  res.send({
    error: 0,
    body: user,
    message: '更新成功'
  });
});

/**
 * 逻辑删除用户（标记删除）
 */
const softDeleteUser = catchAsync(async (req, res) => {
  console.log('逻辑删除用户，用户ID:', req.params.userId);
  
  await userService.softDeleteUserById(req.params.userId);
  
  console.log('成功逻辑删除用户，用户ID:', req.params.userId);
  
  res.send({
    error: 0,
    body: null,
    message: '用户已成功删除'
  });
});

/**
 * 物理删除用户
 */
const deleteUser = catchAsync(async (req, res) => {
  console.log('物理删除用户，用户ID:', req.params.userId);
  
  await userService.deleteUserById(req.params.userId);
  
  console.log('成功物理删除用户，用户ID:', req.params.userId);
  
  res.send({
    error: 0,
    body: null,
    message: '用户已永久删除'
  });
});

/**
 * 获取微信小程序用户健康信息
 * 用于小程序获取当前登录用户的健康档案
 */
const getMiniprogramUserProfile = catchAsync(async (req, res) => {
  console.log('获取用户健康信息，请求用户:', JSON.stringify({
    id: req.user?.id,
    role: req.user?.role,
    isAuthenticated: !!req.user
  }));
  
  if (!req.user || !req.user.id) {
    throw new ApiError(httpStatus.UNAUTHORIZED, '请先登录');
  }
  
  const userId = req.user.id;
  console.log('尝试获取用户健康信息，用户ID:', userId);
  
  const user = await userService.getUserById(userId);
  
  if (!user) {
    console.error('用户健康信息未找到，用户ID:', userId);
    throw new ApiError(httpStatus.NOT_FOUND, '用户信息未找到');
  }
  
  console.log('成功获取用户健康信息，用户ID:', userId);
  
  // 构建返回数据
  const userProfile = {
    userId: user.id,
    nickname: user.nickname || '',
    avatar: user.avatar || '',
    gender: user.gender || 0,
    height: user.height || 0,
    weight: user.weight || 0,
    age: user.age || 0,
    activityLevel: user.activityLevel || 1,
    goal: user.goal || '健康饮食',
    dailyCalorieGoal: user.dailyCalorieGoal || 0
  };
  
  res.send({
    error: 0,
    body: userProfile,
    message: ''
  });
});

/**
 * 更新微信小程序用户健康信息
 * 用于小程序更新当前登录用户的健康档案
 */
const updateMiniprogramUserProfile = catchAsync(async (req, res) => {
  console.log('更新用户健康信息，请求用户:', JSON.stringify({
    id: req.user?.id,
    role: req.user?.role,
    isAuthenticated: !!req.user
  }));
  
  if (!req.user || !req.user.id) {
    throw new ApiError(httpStatus.UNAUTHORIZED, '请先登录');
  }
  
  const userId = req.user.id;
  console.log('尝试更新用户健康信息，用户ID:', userId, '请求数据:', JSON.stringify(req.body));
  
  // 更新用户信息
  try {
    const user = await userService.updateUserById(userId, req.body);
    
    if (!user) {
      console.error('更新用户健康信息失败，用户ID:', userId);
      throw new ApiError(httpStatus.NOT_FOUND, '更新用户信息失败');
    }
    
    console.log('成功更新用户健康信息，用户ID:', userId);
    
    // 构建返回数据
    const userProfile = {
      userId: user.id,
      nickname: user.nickname || '',
      avatar: user.avatar || '',
      gender: user.gender || 0,
      height: user.height || 0,
      weight: user.weight || 0,
      age: user.age || 0,
      activityLevel: user.activityLevel || 1,
      goal: user.goal || '健康饮食',
      dailyCalorieGoal: user.dailyCalorieGoal || 0
    };
    
    res.send({
      error: 0,
      body: userProfile,
      message: '更新成功'
    });
  } catch (error) {
    console.error('更新用户健康信息异常:', error.message);
    throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, `更新失败: ${error.message}`);
  }
});

/**
 * 上传用户头像
 * 接收并处理用户头像上传请求
 */
const uploadAvatar = catchAsync(async (req, res) => {
  console.log('上传用户头像，请求发起者:', JSON.stringify({
    id: req.user?.id,
    userType: req.user?.userType,
    isAuthenticated: !!req.user
  }));
  console.log('请求体 (req.body):', req.body);

  if (!req.file) {
    throw new ApiError(httpStatus.BAD_REQUEST, '未检测到上传的图片文件');
  }

  let targetUserId;
  const specifiedUserId = req.body.userId;

  if (specifiedUserId) {
    // 如果请求体中指定了 userId，说明是管理员在尝试更新特定用户的头像
    console.log(`管理员尝试更新指定用户 ${specifiedUserId} 的头像`);
    if (!req.user || req.user.userType !== 'admin') {
      throw new ApiError(httpStatus.FORBIDDEN, '只有管理员才能更新指定用户的头像');
    }
    targetUserId = specifiedUserId;
  } else {
    // 如果请求体中没有指定 userId，说明是用户在更新自己的头像
    if (!req.user || !req.user.id) {
      // 理论上 auth() 中间件已经保证了 req.user.id 存在
      throw new ApiError(httpStatus.UNAUTHORIZED, '请先登录');
    }
    targetUserId = req.user.id;
    console.log(`用户 ${targetUserId} 尝试更新自己的头像`);
  }
  
  console.log(`最终目标用户ID (用于 userService.updateUserById): ${targetUserId}`);
  
  const avatarUrl = `/uploads/avatars/${req.file.filename}`;
  console.log(`尝试更新用户 ${targetUserId} 的头像URL为: ${avatarUrl}`);

  await userService.updateUserById(targetUserId, { avatar: avatarUrl });

  res.send({
    error: 0,
    body: {
      avatarUrl,
    },
    message: '头像上传成功'
  });
});

module.exports = {
  createUser,
  getUsers,
  getUser,
  updateUser,
  softDeleteUser,
  deleteUser,
  getMiniprogramUserProfile,
  updateMiniprogramUserProfile,
  uploadAvatar,
}; 